#include <iostream>
#include <string>
#include <sstream>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>

#include "csocket.h"

csocket::csocket(int domain, int type, int protocol, int buffer_size)
{
	c_socket = socket(domain, type, protocol);
	c_stream = (type == SOCK_STREAM);
	c_buffer_size = buffer_size;
}

csocket::csocket(int socket, int buffer_size, bool stream)
{
	c_socket = socket;
	c_buffer_size = buffer_size;
	c_stream = stream;
}

csocket::~csocket()
{
	//rien a faire...
}

bool csocket::cconnect(const struct sockaddr *my_addr, socklen_t addrlen)
{
	return (connect(c_socket, my_addr, addrlen) == -1) ? false : true;
}

bool csocket::cbind(const struct sockaddr *my_addr, socklen_t addrlen)
{
	return (bind(c_socket, my_addr, addrlen) == -1) ? false : true;
}

bool csocket::clisten(int backlog)
{
	return (listen(c_socket, backlog) == -1) ? false : true;
}

csocket *csocket::caccept(struct sockaddr *addr, socklen_t *addrlen)
{
	int new_socket;
	new_socket = accept(c_socket, addr, addrlen);
	std::cout << "Client détécté" << std::endl;
	if (new_socket >= 0) {
		csocket *result = new csocket(new_socket, c_buffer_size, c_stream);
		return result;
	}
	else
	{
		return NULL;
	}
}

bool csocket::csend(const void *msg, size_t len, int flags)
{
	return (send(c_socket, msg, len, flags) == -1) ? false : true;
}

bool csocket::csend(std::string msg, int flags)
{
	return (send(c_socket, msg.c_str(), msg.length(), flags) == -1) ? false : true;
}

bool csocket::cshutdown(int how)
{
	return (shutdown(c_socket, how) == -1) ? false : true;
}

bool csocket::cclose()
{
	return (close(c_socket) == -1) ? false : true;
}

int csocket::creceive(std::string* message, int flags)
{
	char buffer[c_buffer_size];
	int n;
	do
	{
		n = recv(c_socket, buffer, c_buffer_size, flags);
		(*message) = (*message) + buffer;
	}
	while (n == c_buffer_size);
	if (n > 0)
	{
		return n;
	}
	else
	{
		return -1;
	}
}

void csocket::cset_buffer_size(int buffer_size)
{
	c_buffer_size = buffer_size;
}

int csocket::cget_buffer_size()
{
	return c_buffer_size;
}

bool csocket::cserver_TCP(int port, int backlog)
{
	std::cout << "Initialisation du serveur..." << std::endl;
	struct sockaddr_in recv_socket_addr;

	bzero(&recv_socket_addr, sizeof(recv_socket_addr));

	recv_socket_addr.sin_family = AF_INET;
	recv_socket_addr.sin_port = htons(port);
	recv_socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if (cbind((struct sockaddr*) &recv_socket_addr, sizeof(recv_socket_addr)) == false) {
		return false;
	}
	std::cout << "Socket bindée" << std::endl;
	
	if (clisten(backlog) == false) {
		return false;
	}
	
	std::cout << "Listen activé" << std::endl;
	
	return true;
}
